package cn.fl.mcr.controller;

import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mcr.transform.McrMarketTempletVOTransform;
import cn.fl.mcr.vo.McrMarketTempletVO;
import cn.fl.system.constant.SysLogConstant;
import cn.lionbridgecapital.loan.model.base.Pager;
import cn.lionbridgecapital.loan.model.condition.McrMarketTempletQC;
import cn.lionbridgecapital.loan.model.dto.McrMarketTempletDTO;
import cn.lionbridgecapital.loan.model.enu.IsDeleteType;
import cn.lionbridgecapital.loan.model.enu.IsSuccessType;
import cn.lionbridgecapital.loan.service.api.IMcrMarketTempletApiService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author yangqh521
 * @date 2020/6/24
 * @desp 营销模板
 */
@RestController
@RequestMapping("/mcr/mcrMarketTemplet")
public class McrMarketTempletController {

    private static final Logger logger = LoggerFactory.getLogger(McrMarketTempletController.class);

    @Autowired
    private IMcrMarketTempletApiService mcrMarketTempletApiService;

    /**
     * 日期参数绑定
     * @param binder
     */
    @InitBinder
    public void initBinder(ServletRequestDataBinder binder){
        CustomDateEditor customDateEditor = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true);
        binder.registerCustomEditor(Date.class, customDateEditor);
    }


    /**
     * 到列表页面
     */
    @RequestMapping("/toListPage.do")
    public ModelAndView toListPage() {
        ModelAndView view = new ModelAndView("/mcr/mcrMarketTemplet/mcrMarketTempletList");
        BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到添加页面
     */
    @RequestMapping("/toAddPage.do")
    public ModelAndView toAddPage(Long id) {
        ModelAndView view = new ModelAndView("/mcr/mcrMarketTemplet/mcrMarketTempletAdd");
        BaseLogUtils.info(logger, "toAddPage", "跳转到新增页面, [id="+id+"]", CurrentThreadContext.getCurrentUserName());
        view.addObject("id", id);
        return view;


    }

    /**
     * 到修改页面
     */
    @RequestMapping("/toModifyPage.do")
    public ModelAndView toModifyPage(Long id) {
        ModelAndView view = new ModelAndView("/mcr/mcrMarketTemplet/mcrMarketTempletModify");
        BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面, [id="+id+"]", CurrentThreadContext.getCurrentUserName());
        view.addObject("id", id);
        return view;
    }

    /**
     * 到预览页面
     */
    @RequestMapping("/toPreviewPage.do")
    public ModelAndView toPreviewPage(Long id) {
        ModelAndView view = new ModelAndView("/mcr/mcrMarketTemplet/mcrMarketTempletPreview");
        BaseLogUtils.info(logger, "toModifyPage", "跳转到预览页面, [id="+id+"]", CurrentThreadContext.getCurrentUserName());
        view.addObject("id", id);
        return view;
    }


    /**
     * 列表数据
     * @param page
     * @param pagesize
     * @return
     */
    @RequestMapping("/initList.do")
    public ListPageVO initList(@RequestParam(defaultValue = "1") Integer page,
                        @RequestParam(defaultValue = "10")Integer pagesize,
                        McrMarketTempletQC qc) {
        // 查询
        Pager queryPager = new Pager();
        queryPager.setCurrentPage(page);
        queryPager.setEveryPage(pagesize);
        qc.setIsDel(IsDeleteType.UN_DELETE.getCode());
        queryPager.setCondition(qc);
        BaseLogUtils.info(logger, "initList", "获取列表, queryPager:" + JSONObject.toJSONString(queryPager),
                CurrentThreadContext.getCurrentUserName());
        // 初始化返回数据
        Integer totalCount = 0;
        List<McrMarketTempletVO> resultList = new ArrayList();
        try {
            Pager resultPager = mcrMarketTempletApiService.doFindMcrMarketTempletDTOForPage(queryPager);
            BaseLogUtils.info(logger, "initList", "获取列表, resultPager:" + JSONObject.toJSONString(resultPager),
                    CurrentThreadContext.getCurrentUserName());
            // 处理返回数据
            if(resultPager != null && CollectionUtils.isNotEmpty(resultPager.getResultList())){
                totalCount = resultPager.getTotalCount();
                resultList = McrMarketTempletVOTransform.toVOList((List<McrMarketTempletDTO>)resultPager.getResultList());
            }
        } catch (Exception e) {
            BaseLogUtils.error(logger, "initList", "获取列表异常, queryPager:" + JSONObject.toJSONString(queryPager),
                    CurrentThreadContext.getCurrentUserName(), e);
        }
        // 返回数据
        ListPageVO<McrMarketTempletVO> listPageVO = new ListPageVO<McrMarketTempletVO>(resultList, totalCount);
        BaseLogUtils.info(logger, "initList", "获取列表, listPageVO:" + JSONObject.toJSONString(listPageVO),
                CurrentThreadContext.getCurrentUserName());
        return listPageVO;
    }

    /**
     * 单条新增新增数据
     * @return
     */
    @RequestMapping("/add.do")
    public DataResultVO add(McrMarketTempletVO vo, String fileParams) {
        DataResultVO resultVO = new DataResultVO(IsSuccessType.SUCCESS.getCode(), SysLogConstant.LOG_CMM_DELETE_SUCC);
        BaseLogUtils.info(logger, "add", "添加模板, vo:" + JSONObject.toJSONString(vo));
        BaseLogUtils.info(logger, "add", "添加模板, fileParams:" + JSONObject.toJSONString(fileParams));

        McrMarketTempletDTO dto = McrMarketTempletVOTransform.toDTO(vo);
        dto.setCrtTm(new Date());
        dto.setCrtTm(new Date());
        dto.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
        dto.setIsDel(IsDeleteType.UN_DELETE.getCode());

        DataResultDTO dataResultDTO = getPathFromFileParams(dto, fileParams);
        if(!IsSuccessType.SUCCESS.getCode().equals(dataResultDTO.getSuccess())){
            resultVO.setSuccess(IsSuccessType.FAIL.getCode());
            resultVO.setInfo(dataResultDTO.getInfo());
            return resultVO;
        }

        BaseLogUtils.info(logger, "add", "添加模板, dto:" + JSONObject.toJSONString(dto));

        try {
            mcrMarketTempletApiService.addMcrMarketTempletDTO(dto);
        } catch (Exception e) {
            BaseLogUtils.error(logger, "add", "添加模板异常",
                    CurrentThreadContext.getCurrentUserName(), e);
            resultVO.setSuccess(IsSuccessType.FAIL.getCode());
            resultVO.setInfo("添加模板失败！");
        }
        BaseLogUtils.info(logger, "add", "添加模板, resultVO:" + JSONObject.toJSONString(resultVO),
                CurrentThreadContext.getCurrentUserName());
        return resultVO;
    }

    /**
     * 主键获取
     * @return
     */
    @RequestMapping("/getById.do")
    public DataResultVO getById(Long id) {

        DataResultVO resultVO = new DataResultVO(IsSuccessType.SUCCESS.getCode(), SysLogConstant.LOG_CMM_OPERATE_SUCC);
        BaseLogUtils.info(logger, "getById", "查询数据, id:" + id, CurrentThreadContext.getCurrentUserName());

        McrMarketTempletDTO dto = null;
        try {
            dto = mcrMarketTempletApiService.doFindMcrMarketTempletDTOById(id);
            BaseLogUtils.info(logger, "getById", "查询模板, dto:" + JSONObject.toJSONString(dto));
        } catch (Exception e) {
            BaseLogUtils.error(logger, "getById", "查询数据, id:" + id,
                    CurrentThreadContext.getCurrentUserName(), e);
            resultVO.setSuccess(IsSuccessType.FAIL.getCode());
            resultVO.setInfo("查询数据失败！");
        }
        if(dto == null){
            resultVO.setSuccess(IsSuccessType.FAIL.getCode());
            resultVO.setInfo("不存在此模板！");
        }
        resultVO.setData(McrMarketTempletVOTransform.toVO(dto));
        BaseLogUtils.info(logger, "getById", "查询数据, resultVO:" + JSONObject.toJSONString(resultVO),
                CurrentThreadContext.getCurrentUserName());
        return resultVO;
    }

    /**
     * 修改功能
     * @return
     */
    @RequestMapping("/modify.do")
    public DataResultVO modify(McrMarketTempletVO vo, String fileParams) {
        BaseLogUtils.info(logger, "modify", "修改模板, vo:" + JSONObject.toJSONString(vo));
        BaseLogUtils.info(logger, "modify", "修改模板, fileParams:" + JSONObject.toJSONString(fileParams));

        DataResultVO resultVO = new DataResultVO(IsSuccessType.SUCCESS.getCode(), SysLogConstant.LOG_CMM_OPERATE_SUCC);
        McrMarketTempletDTO dto = McrMarketTempletVOTransform.toDTO(vo);
        dto.setMdfTm(new Date());
        dto.setMdfUsrId(CurrentThreadContext.getCurrentUserId());

        DataResultDTO dataResultDTO = getPathFromFileParams(dto, fileParams);
        if(!IsSuccessType.SUCCESS.getCode().equals(dataResultDTO.getSuccess())){
            resultVO.setSuccess(IsSuccessType.FAIL.getCode());
            resultVO.setInfo(dataResultDTO.getInfo());
            return resultVO;
        }

        BaseLogUtils.info(logger, "modify", "修改模板, dto:" + JSONObject.toJSONString(dto));

        try {
            mcrMarketTempletApiService.modifyMcrMarketTempletDTO(dto);
        } catch (Exception e) {
            BaseLogUtils.error(logger, "modify", "修改模板异常, dto:" + JSONObject.toJSONString(dto),
                    CurrentThreadContext.getCurrentUserName(), e);
            resultVO.setSuccess(IsSuccessType.FAIL.getCode());
            resultVO.setInfo("修改模板失败！");
        }
        BaseLogUtils.info(logger, "modify", "修改模板, resultVO:" + JSONObject.toJSONString(resultVO),
                CurrentThreadContext.getCurrentUserName());
        return resultVO;
    }

    /**
     * 处理图片链接
     * @param dto
     * @param fileParams
     * @return
     */
    private DataResultDTO getPathFromFileParams(McrMarketTempletDTO dto, String fileParams) {
        DataResultDTO dataResultDTO = new DataResultDTO(IsSuccessType.SUCCESS.getCode());

        if(StringUtils.isBlank(fileParams)){
            return dataResultDTO;
        }
        JSONArray jsonArray = JSONObject.parseArray(fileParams);
        if(jsonArray.size() != 3){
            dataResultDTO.setSuccess(IsSuccessType.FAIL.getCode());
            dataResultDTO.setInfo("请上传上|中|下三张图片！");
            return dataResultDTO;
        }
        String topImgPath = jsonArray.getJSONObject(0).getString(SysUlFilesRecConstant.REQUEST_PARAM_FILE_PATH);
        String midImgPath = jsonArray.getJSONObject(1).getString(SysUlFilesRecConstant.REQUEST_PARAM_FILE_PATH);
        String botImgPath = jsonArray.getJSONObject(2).getString(SysUlFilesRecConstant.REQUEST_PARAM_FILE_PATH);

        dto.setTopImgPath(topImgPath);
        dto.setMidImgPath(midImgPath);
        dto.setBotImgPath(botImgPath);
        BaseLogUtils.info(logger, "getPathFromFileParams", "获取图片链接, dto:" + JSONObject.toJSONString(dto));

        return dataResultDTO;
    }

    /**
     * 修改功能
     * @return
     */
    @RequestMapping("/switch.do")
    public DataResultVO switchDo(Long id, Integer isValid) {
        BaseLogUtils.info(logger, "switch", "开启数据, id:" + id + ", isValid:" + isValid);

        DataResultVO resultVO = new DataResultVO(IsSuccessType.SUCCESS.getCode(), SysLogConstant.LOG_CMM_OPERATE_SUCC);
        try {
            mcrMarketTempletApiService.modifyIsValidOfMcrMarketTemplet(id, isValid);
        } catch (Exception e) {
            BaseLogUtils.error(logger, "switch", "开启数据异常, id:" + id + ", isValid:" + isValid,
                    CurrentThreadContext.getCurrentUserName(), e);
            resultVO.setSuccess(IsSuccessType.FAIL.getCode());
            resultVO.setInfo("开启失败！");
        }
        BaseLogUtils.info(logger, "switch", "开启数据, resultVO:" + JSONObject.toJSONString(resultVO),
                CurrentThreadContext.getCurrentUserName());
        return resultVO;
    }

}
